package cn.com.xuxiaowei.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author xuxiaowei
 */
@Slf4j
@Configuration
public class DynamicDataSourceConfig {

	private MultipleDataSourceConfig multipleDataSourceConfig;

	private MultipleDataSource multipleDataSource;

	@Autowired
	public void setMultipleDataSourceConfig(MultipleDataSourceConfig multipleDataSourceConfig) {
		this.multipleDataSourceConfig = multipleDataSourceConfig;
	}

	@Autowired
	public void setMultipleDataSource(MultipleDataSource multipleDataSource) {
		this.multipleDataSource = multipleDataSource;
	}

	public void setDefaultTargetDataSource(DataSource defaultTargetDataSource) {
		log.info("更新默认数据源");
		multipleDataSource.setDefaultTargetDataSource(defaultTargetDataSource);
		multipleDataSource.afterPropertiesSet();
	}

	public void setLenientFallback(boolean lenientFallback) {
		log.info("设置宽松模式");
		multipleDataSource.setLenientFallback(lenientFallback);
		multipleDataSource.afterPropertiesSet();
	}

	public boolean removeDataSource(String name) {
		log.info("删除数据源：{}", name);

		Map<Object, Object> targetDataSources = multipleDataSourceConfig.getTargetDataSources();
		Object remove = targetDataSources.remove(name);
		if (remove == null) {
			log.warn("删除数据源：{} 失败", name);
			return false;
		}

		multipleDataSource.setTargetDataSources(targetDataSources);
		multipleDataSource.afterPropertiesSet();

		log.info("删除数据源：{}, 成功", name);

		return true;
	}

	public void addDataSource(String name, DataSource dataSource) {
		log.info("添加/更新数据源：{}", name);

		Map<Object, Object> targetDataSources = multipleDataSourceConfig.getTargetDataSources();
		targetDataSources.put(name, dataSource);

		multipleDataSource.setTargetDataSources(targetDataSources);
		multipleDataSource.afterPropertiesSet();

		log.info("添加/更新数据源：{}, 成功", name);
	}

}
